#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>

int main()
{
	int fd = open("b.txt",O_RDWR|O_CREAT,0666);
	if(fd==-1){
		perror("open");
		return -1;
	}	
	struct flock lock;
	lock.l_type = F_WRLCK;  //写锁
	lock.l_whence = SEEK_SET;//文件开头
	lock.l_start = 30;//从文件头锁定
	lock.l_len = 10;//锁定20字节
	lock.l_pid = -1;

	//加锁
	//不阻塞加锁
	//int res = fcntl(fd,F_SETLK,&lock);
	//阻塞加锁，原地等待直到加锁成功
	int res = fcntl(fd,F_SETLKW,&lock);

	if(res==-1){
		printf("failed!!\n");
		return ;
	}
	else{
		printf("success!!\n");
	}
	//操作
	write(fd,"hello",5);
	sleep(5);
	
	//解锁
	lock.l_type=F_UNLCK;
	fcntl(fd,F_SETLK,&lock);
	printf("success!\n");

	close(fd);

}
